<template>
  <div class="page-wrapper">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <div class="nav-content">
        <div class="nav-left">
          <img src="https://lovechronicle.oss-cn-zhangjiakou.aliyuncs.com/book.jpg" alt="Logo" class="logo">
          <span class="site-name">图书分类</span>
        </div>
        <div class="nav-right">
          <el-button class="back-button" @click="router.back()">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <div class="categories-container">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <!-- 作品分类 -->
        <div class="filter-row">
          <div class="filter-label">作品分类：</div>
          <div class="filter-options">
            <span 
              class="filter-option"
              :class="{ active: selectedCategoryId === null }"
              @click="handleCategorySelect(null)"
            >
              全部
            </span>
            <span 
              v-for="category in staticCategories" 
              :key="category.categoryId"
              class="filter-option"
              :class="{ active: selectedCategoryId === category.categoryId }"
              @click="handleCategorySelect(category)"
            >
              {{ category.categoryName }}
            </span>
          </div>
        </div>

        <!-- 作品字数 -->
        <div class="filter-row">
          <div class="filter-label">作品字数：</div>
          <div class="filter-options">
            <span 
              v-for="option in wordCountOptions" 
              :key="option.value"
              class="filter-option"
              :class="{ active: selectedWordCount === option.value }"
              @click="handleWordCountChange(option.value)"
            >
              {{ option.label }}
            </span>
          </div>
        </div>
      </div>

      <!-- 排序和展示模式 -->
      <div class="control-bar">
        <div class="sort-options">
          <span class="sort-option" :class="{ active: sortBy === 'collection' }" @click="handleSort('collection')">
            <span class="radio-dot"></span>
            <el-icon><Collection /></el-icon>
            按收藏数
          </span>
          <span class="sort-option" :class="{ active: sortBy === 'wordCount' }" @click="handleSort('wordCount')">
            <span class="radio-dot"></span>
            <el-icon><Document /></el-icon>
            按总字数
          </span>
        </div>
        <div class="view-mode">
          <el-icon 
            class="mode-icon" 
            :class="{ active: viewMode === 'grid' }"
            @click="handleViewModeChange('grid')"
          >
            <Grid />
          </el-icon>
          <el-icon 
            class="mode-icon" 
            :class="{ active: viewMode === 'list' }"
            @click="handleViewModeChange('list')"
          >
            <List />
          </el-icon>
        </div>
      </div>

      <!-- 加载状态显示 -->
      <div v-if="loading" class="books-loading">
        <el-skeleton :loading="loading" animated>
          <template #template>
            <div class="books-skeleton" :class="{ 'list-mode': viewMode === 'list' }">
              <div v-for="i in 8" :key="i" class="skeleton-item">
                <el-skeleton-item v-if="viewMode === 'grid'" variant="image" style="width: 100%; height: 260px;" />
                <template v-else>
                  <div class="list-skeleton">
                    <el-skeleton-item variant="image" style="width: 120px; height: 160px;" />
                    <div class="list-content">
                      <el-skeleton-item variant="text" style="width: 50%" />
                      <el-skeleton-item variant="text" style="width: 30%" />
                      <el-skeleton-item variant="text" style="width: 80%" />
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 图书列表 -->
      <div v-else class="books-section">
        <transition-group 
          name="book-list" 
          :tag="viewMode === 'grid' ? 'div' : 'ul'" 
          :class="[viewMode === 'grid' ? 'books-grid' : 'books-list']"
        >
          <div 
            v-for="book in filteredBooks" 
            :key="book.id" 
            :class="[viewMode === 'grid' ? 'book-item' : 'book-item-list']"
            @click="handleBookClick(book)"
          >
            <div class="book-cover">
              <el-image 
                :src="book.cover" 
                fit="cover"
                loading="lazy"
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="book-info">
              <h3 class="book-title">{{ book.title }}</h3>
              <p class="book-author">{{ book.author }}</p>
              <p class="book-description">{{ book.description }}</p>
              <div class="book-meta">
                <span class="meta-item">
                  <el-icon><Document /></el-icon>
                  {{ book.wordCount }}万字
                </span>
                <span class="meta-item">
                  <el-icon><StarFilled /></el-icon>
                  {{ book.rating }}分
                </span>
              </div>
            </div>
          </div>
        </transition-group>

        <!-- 分页器 -->
        <div class="pagination-container" v-if="total > pageSize">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[20, 25, 35, 40]"
            :total="total"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  StarFilled, Picture, Document, Collection, Grid, List, ArrowLeft
} from '@element-plus/icons-vue'
import { getBookCategories, getBooksByFilter } from '@/api/user'

const router = useRouter()
const loading = ref(false)
const selectedCategoryId = ref(null)
const selectedWordCount = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const books = ref([])
const sortBy = ref('collection') // collection 或 wordCount

// 分类数据
const staticCategories = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    loading.value = true
    const res = await getBookCategories()
    if (res.code === 0) {
      staticCategories.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取分类失败')
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  } finally {
    loading.value = false
  }
}

// 获取图书数据
const fetchBooks = async () => {
  try {
    loading.value = true
    
    // 处理字数范围
    let minWordCount = null
    let maxWordCount = null
    if (selectedWordCount.value !== 'all') {
      const [min, max] = selectedWordCount.value.split('-')
      minWordCount = Number(min)
      maxWordCount = max === '+' ? null : Number(max)
    }

    const params = {
      categoryId: selectedCategoryId.value || '',
      minWordCount: minWordCount || '',
      maxWordCount: maxWordCount || '',
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      orderBy: sortBy.value === 'collection' ? '1' : '2' // 1-按收藏数，2-按字数
    }

    const res = await getBooksByFilter(params)
    if (res.code === 0) {
      books.value = res.data.results.map(book => ({
        ...book,
        id: book.bookId,
        cover: book.coverImage,
        rating: book.averageRating,
        wordCount: book.wordCount
      }))
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取图书失败')
    }
  } catch (error) {
    console.error('获取图书失败:', error)
    ElMessage.error('获取图书失败')
  } finally {
    loading.value = false
  }
}

// 监听筛选条件变化
watch([selectedCategoryId, selectedWordCount, sortBy, currentPage, pageSize], () => {
  fetchBooks()
})

// 页面加载时获取数据
onMounted(() => {
  fetchCategories()
  fetchBooks()
})

// 获取选中的分类
const selectedCategory = computed(() => {
  return staticCategories.value.find(c => c.categoryId === selectedCategoryId.value)
})

// 根据筛选条件过滤图书
const filteredBooks = computed(() => {
  return books.value
})

// 处理分类选择
const handleCategorySelect = (category) => {
  selectedCategoryId.value = category ? category.categoryId : null
  currentPage.value = 1
}

// 处理字数范围变更
const handleWordCountChange = (value) => {
  selectedWordCount.value = value
  currentPage.value = 1
}

// 处理排序方式改变
const handleSort = (type) => {
  sortBy.value = type
  currentPage.value = 1
}

// 处理页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变更
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理图书点击
const handleBookClick = (book) => {
  router.push({
    path: '/user/book-detail',
    query: { id: book.id }
  })
}

// 字数范围选项
const wordCountOptions = [
  { label: '全部', value: 'all' },
  { label: '30万以下', value: '0-30' },
  { label: '30万-50万', value: '30-50' },
  { label: '50万-100万', value: '50-100' },
  { label: '100万-200万', value: '100-200' },
  { label: '200万以上', value: '200+' }
]

// 添加视图模式状态
const viewMode = ref('grid') // 默认网格视图

// 处理视图模式切换
const handleViewModeChange = (mode) => {
  viewMode.value = mode
}
</script>

<style scoped>
.page-wrapper {
  min-height: 100vh;
  background: #fff;
}

.nav-header {
  background: #fff;
  padding: 0 20px;
  border-bottom: 1px solid #f0f0f0;
}

.nav-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.site-name {
  font-size: 20px;
  color: #333;
}

.nav-right {
  display: flex;
  align-items: center;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 20px;
  transition: all 0.3s ease;
  background-color: #f2f3f5;
  border: none;
  color: #606266;
}

.back-button:hover {
  background-color: #e4e7ed;
  color: #409eff;
}

.back-button .el-icon {
  font-size: 16px;
}

.categories-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.filter-row:last-child {
  border-bottom: none;
}

.filter-label {
  width: 100px;
  color: #666;
  font-size: 14px;
  padding-top: 4px;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-option {
  padding: 6px 12px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.filter-option:hover {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.filter-option.active {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

/* 移除单选框相关样式 */
.radio-dot,
.radio-dot::after,
.filter-option:hover .radio-dot,
.filter-option.active .radio-dot,
.filter-option.active .radio-dot::after {
  display: none;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.book-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.book-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.book-cover {
  height: 260px;
  overflow: hidden;
}

.book-cover :deep(.el-image) {
  width: 100%;
  height: 100%;
  transition: transform 0.3s;
}

.book-item:hover .book-cover :deep(.el-image) {
  transform: scale(1.05);
}

.book-info {
  padding: 12px;
}

.book-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-author {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px;
}

.book-description {
  font-size: 13px;
  color: #999;
  margin: 0 0 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}

.book-meta {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  padding: 30px 0;
  display: flex;
  justify-content: center;
}

/* 动画效果 */
.book-list-enter-active,
.book-list-leave-active {
  transition: all 0.5s ease;
}

.book-list-enter-from,
.book-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .categories-container {
    padding: 10px;
  }

  .filter-container {
    padding: 10px;
  }

  .filter-label {
    width: 80px;
  }

  .filter-options {
    gap: 8px;
  }

  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }

  .book-cover {
    height: 220px;
  }
}

.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.sort-options {
  display: flex;
  gap: 10px;
}

.sort-option {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.sort-option:hover {
  color: var(--el-color-primary);
}

.sort-option.active {
  color: var(--el-color-primary);
}

.sort-option .radio-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  background: #dcdfe6;
  transition: all 0.3s;
}

.sort-option:hover .radio-dot {
  background: var(--el-color-primary-light-3);
}

.sort-option.active .radio-dot {
  background: var(--el-color-primary);
}

.view-mode {
  display: flex;
  gap: 10px;
}

.mode-icon {
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s;
}

.mode-icon:hover {
  color: var(--el-color-primary);
}

.mode-icon.active {
  color: var(--el-color-primary);
}

/* 列表视图样式 */
.books-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px 0;
  list-style: none;
  margin: 0;
}

.book-item-list {
  display: flex;
  gap: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;
}

.book-item-list:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.book-item-list .book-cover {
  width: 120px;
  height: 160px;
  flex-shrink: 0;
}

.book-item-list .book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.book-item-list .book-title {
  font-size: 18px;
  margin-bottom: 12px;
}

.book-item-list .book-description {
  -webkit-line-clamp: 3;
  margin-bottom: 16px;
}

.book-item-list .book-meta {
  margin-top: auto;
}

/* 响应式设计补充 */
@media (max-width: 768px) {
  .book-item-list {
    flex-direction: column;
    gap: 12px;
  }

  .book-item-list .book-cover {
    width: 100%;
    height: 200px;
  }
}

/* 添加全局加载状态样式 */
.global-loading {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.books-skeleton {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.el-skeleton-item {
  border-radius: 8px;
}

.books-loading {
  padding: 20px 0;
}

.books-skeleton {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.books-skeleton.list-mode {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.skeleton-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.list-skeleton {
  display: flex;
  gap: 20px;
  padding: 16px;
}

.list-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

@media (max-width: 768px) {
  .list-skeleton {
    flex-direction: column;
  }
  
  .list-skeleton .el-skeleton-item {
    width: 100% !important;
  }
}
</style> 